<template>
	<view class="qr-generator-container">
		<view>
			<tki-qrcode ref="qrcode" :cid="cid" :val="val" :size="size" :unit="unit" :background="background"
				:foreground="foreground" :pdground="pdground" :icon="icon" :iconsize="iconsize" :lv="lv" :onval="onval"
				:loadMake="loadMake" :showLoading="showLoading" :loadingText="loadingText" @result="qrR" />
		</view>
	</view>
</template>

<script>
	import TkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";

	export default {
		name: 'QRLightGenerator',
		components: {
			TkiQrcode
		},

		props: {
			url: { type: String, default: 'https://example.com' },
			showLoading: { type: Boolean, default: true },
			loadingText: { type: String, default: '生成中...' },
			size: { type: Number, default: 200 },
			background: { type: String, default: '#ffffff' },
			foreground: { type: String, default: '#000000' },
			pdground: { type: String, default: '#000000' },
			icon: { type: String, default: '' },
			iconsize: { type: Number, default: 40 },
			lv: { type: Number, default: 3 }
		},

		data() {
			return {
				cid: `qr-${Date.now()}`,
				val: '',
				unit: 'px',
				onval: true,
				loadMake: true,
				usingComponents: false,
				qrCodeResult: null,
				downloadStatus: ''
			};
		},

		methods: {

			// ✅ generateQR：增加清理旧文件
			generateQR() {
				return new Promise(async (resolve, reject) => {
					// 校验
					if (!this.url) {
						uni.showToast({ title: '链接为空', icon: 'none' });
						return reject('链接为空');
					}
					if (!/^https:\/\//i.test(this.url)) {
						uni.showToast({ title: '仅支持 HTTPS 链接', icon: 'none' });
						return reject('仅支持 HTTPS 链接');
					}

					// ✅ 1. 清理所有旧的临时二维码文件
					await this.clearOldTempFiles();

					// ✅ 2. 设置新值触发生成
					this.val = this.url;

					// ✅ 3. resolve 可以继续保留（但实际应在 qrR 中处理）
					resolve(this.val);
				});
			},

			// ✅ 新增：清理所有旧的临时文件
			clearOldTempFiles() {
				return new Promise((resolve) => {
					const fs = uni.getFileSystemManager();
					const dir = uni.env.USER_DATA_PATH;

					// 读取目录下所有文件
					fs.readdir({
						dirPath: dir,
						success: (res) => {
							res.files.forEach(file => {
								// 删除所有以 qrcode_ 开头的文件（你生成的）
								if (file.startsWith('qrcode_')) {
									const filePath = `${dir}/${file}`;
									fs.unlink({
										filePath,
										success: () => console.log('已清理旧文件:', filePath),
										fail: err => console.warn('清理失败:', err)
									});
								}
							});
							resolve();
						},
						fail: () => resolve() // 失败也不阻塞
					});
				});
			},

			// 接收二维码生成结果
			qrR(path) {
				this.qrCodeResult = path;
				this.downloadStatus = '';
				this.$emit('generated', path);
			},

			// 清除二维码（保留原逻辑）
			clearQRCode() {
				if (this.$refs.qrcode) {
					this.$refs.qrcode._clear();
				}
				this.qrCodeResult = null;
				this.val = '';
				this.downloadStatus = '';
				this.$emit('cleared');
			},

			// 将 base64 转为临时文件路径（用于保存）
			base64ToTempFile(base64Data) {
				return new Promise((resolve, reject) => {
					const base64 = base64Data.split(',')[1];
					if (!base64) return reject(new Error('Invalid base64'));

					const fs = uni.getFileSystemManager();
					// ✅ 文件名带上时间戳
					const filePath = `${uni.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;

					try {
						const buffer = uni.base64ToArrayBuffer(base64);
						fs.writeFile({
							filePath,
							data: buffer,
							encoding: 'binary',
							success: () => resolve(filePath),
							fail: err => reject(err)
						});
					} catch (err) {
						reject(err);
					}
				});
			}

		},

		mounted() {
			console.log('QRLightGenerator 组件已加载');
			this.clearOldTempFiles(); // ✅ 启动时先清理一次
			  console.log('QRLightGenerator 组件已加载');
		}
	};
</script>